#include <stdint.h>
#include <string.h>
#include <iostream>
#include <string>
#include <map>

#include "raptor-lite/raptor-lite.h"

class SimpleClientHandler : public raptor::ClientHandler {
public:
    SimpleClientHandler() {}
    ~SimpleClientHandler() {}
    void OnNetEvent(raptor::NetEvent ev) {
        switch (ev) {
        case raptor::NetEvent::Null:
            log_info("NetEvent::Null");
            break;
        case raptor::NetEvent::ConnectFailed:
            log_info("NetEvent::ConnectFailed");
            break;
        case raptor::NetEvent::ConnectSuccess:
            log_info("NetEvent::ConnectSuccess");
            break;
        case raptor::NetEvent::Closed:
            log_info("NetEvent::Closed");
            break;
        default:
            break;
        }
    }
    int MessageLength(uint8_t *, size_t size) { return static_cast<int>(size); }
    void OnMessage(const raptor::Slice &s) {
        log_info("simple client OnMessage: %u bytes, [%s]", s.size(), s.ToString().data());
    }
    void OnHeartbeat(raptor::Slice &s) {
        s = std::string("Heartbeat");
        log_debug("prepare heartbeat message");
    }
};

#define MAX_LINE 1024
void str_cli(raptor::Client *conn) {

    char sendline[MAX_LINE];

    while (fgets(sendline, MAX_LINE, stdin) != NULL) {
        conn->SendMsg(sendline, strlen(sendline));

        memset(sendline, 0, MAX_LINE);
    }
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cout << "simple_client <ip:port>" << std::endl;
        return 0;
    }
    RaptorGlobalStartup();

    const char *address = argv[1];

    SimpleClientHandler sc;
    raptor::Property p({
        {raptor::config::kClientHandler, static_cast<raptor::ClientHandler *>(&sc)},
    });

    raptor::Client *client = NULL;
    auto e                 = raptor::CreateClient(p, &client);
    if (e == RAPTOR_ERROR_NONE) {

        client->Start();
        client->Connect(address);
        str_cli(client);

    } else {
        log_error("Failed to create client:%s", e->ToString().c_str());
    }
    DestroyClient(client);

    RaptorGlobalCleanup();
    return 0;
}
